import axios from "axios";
import {Message} from "element-ui";
import router from "../router/index"

// 1、添加请求拦截器，在请求头中加token
axios.interceptors.request.use(
  config => {
    if (localStorage.getItem('token')) {
      config.headers.token = localStorage.getItem('token');
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  });

// 2、响应拦截器
axios.interceptors.response.use(success => {
  if (success.status && success.status === 200) {
    if (success.data.success === false) {
      success.data.message ? Message.error(success.data.message) : Message.error('操作失败！');
    }
    if (success.data.success === true && success.data.message !== '') {
      Message.success(success.data.message);
    }
    return success;
  }
}, error => {
  // 接口调用失败
  let r = null;
  if (error && error.response) {
    let msg = '';
    switch (error.response.data.code) {
      case 400:
        msg = '错误请求'
        break;
      case 401:
        localStorage.removeItem('Authorization');
        msg = '未授权，请重新登录'
        r = '/login';
        break;
      case 403:
        msg = '拒绝访问'
        break;
      case 404:
        msg = '请求错误,未找到该资源'
        // window.location.href = "/NotFound"
        break;
      case 405:
        msg = '请求方法未允许'
        break;
      case 408:
        msg = '请求超时'
        break;
      case 500:
        if (error.response.data.message !== null) {
          msg = error.response.data.message;
        } else
          msg = '服务器出错!'
        break;
      case 501:
        msg = '服务器无法识别请求方法'
        break;
      case 502:
        msg = '网络错误'
        break;
      case 503:
        msg = '服务不可用'
        break;
      case 504:
        msg = '网络超时'
        break;
      case 505:
        msg = 'http版本不支持该请求'
        break;
      default:
        msg = '未知的错误，请联系管理员！'
    }
    // 在某些特定情况下跳转页面
    if (r !== null) {
      router.replace(r).then(r => {
      });
    }
    Message.error({message: msg});
  } else {
    // 超时处理
    if (JSON.stringify(error).includes('timeout')) {
      Message.error({message: '服务器响应超时，请刷新当前页'})
    } else {
      Message.error({message: '未知的错误，请联系管理员！'})
    }
  }
});

/**
 * 封装请求
 */
let base = '';
export const postApi = (url, params) => {
  return axios({
    method: 'post',
    url: `${base}${url}`,
    data: params
  });
};

// get请求
export const getApi = (url, params) => {
  return axios({
    method: 'get',
    url: `${base}${url}`,
    data: params
  });
};

// put请求
export const putApi = (url, params) => {
  return axios({
    method: 'put',
    url: `${base}${url}`,
    data: params
  });
};

// delete请求
export const deleteApi = (url, params) => {
  return axios({
    method: 'delete',
    url: `${base}${url}`,
    data: params
  });
};